"""
事件总线模块 - 实现模块间解耦通信
"""
from typing import Dict, List, Callable, Any
from enum import Enum
import threading

class EventType(Enum):
    """定义系统事件类型"""
    # 串口相关事件
    SERIAL_CONNECTED = "serial_connected"
    SERIAL_DISCONNECTED = "serial_disconnected" 
    SERIAL_DATA_RECEIVED = "serial_data_received"
    
    # 设备相关事件
    DEVICE_CONNECTED = "device_connected"
    DEVICE_DISCONNECTED = "device_disconnected"
    DEVICE_TIME_UPDATED = "device_time_updated"
    DEVICE_SAMPLING_INTERVAL = "device_sampling_interval"
    
    # 传感器数据事件
    SENSOR_DATA_UPDATED = "sensor_data_updated"
    
    # 下载相关事件
    FILE_LIST_RECEIVED = "file_list_received"
    DOWNLOAD_PROGRESS = "download_progress"
    DOWNLOAD_COMPLETE = "download_complete"
    # 配置相关事件
    CONFIG_HEADER_UPDATED = "config_header_updated"

class EventBus:
    """事件总线 - 单例模式"""
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self._listeners: Dict[EventType, List[Callable]] = {}
            self._lock = threading.RLock()
            self._initialized = True
    
    def subscribe(self, event_type: EventType, callback: Callable):
        """订阅事件"""
        with self._lock:
            if event_type not in self._listeners:
                self._listeners[event_type] = []
            self._listeners[event_type].append(callback)
    
    def unsubscribe(self, event_type: EventType, callback: Callable):
        """取消订阅事件"""
        with self._lock:
            if event_type in self._listeners:
                try:
                    self._listeners[event_type].remove(callback)
                except ValueError:
                    pass
    
    def emit(self, event_type: EventType, data: Any = None):
        """发布事件"""
        with self._lock:
            if event_type in self._listeners:
                # print(f"[event] 触发事件 {event_type}，数据: {data}")
                for callback in self._listeners[event_type][:]:  # 创建副本避免迭代时修改
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"事件处理错误 {event_type}: {e}")

# 全局事件总线实例
event_bus = EventBus()